﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.DataVisualization.Charting;

/*
 * Op basis van: http://www.codeproject.com/Articles/33902/Streaming-Chart-Images-as-FileResult-from-MVC-Cont
 */
namespace MMCInfo.Lib
{
    public class ChartResult : FileResult
    {
        private const int _bufferSize = 0x1000;

        public ChartResult(Chart chart, ChartImageFormat imageFormat)
            : base(MapImageFormatToMimeType(imageFormat))
        {
            if (null == chart) throw new ArgumentNullException("chart");

            this.Chart = chart;
            this.ImageFormat = imageFormat;
        }

        public ChartResult(Chart chart)
            : this(chart, ChartImageFormat.Png)
        {
        }

        public Chart Chart
        {
            get;
            private set;
        }

        public ChartImageFormat ImageFormat
        {
            get;
            private set;
        }

        private static string MapImageFormatToMimeType(ChartImageFormat imageFormat)
        {
            switch (imageFormat)
            {
                case ChartImageFormat.Png:
                    return "image/png";

                case ChartImageFormat.Jpeg:
                    return "image/jpeg";

                case ChartImageFormat.Gif:
                    return "image/gif";

                case ChartImageFormat.Bmp:
                    return "image/bmp";

                case ChartImageFormat.Tiff:
                    return "image/tiff";

                default:
                    throw new ArgumentException("Unsupported format");
            }
        }

        protected override void WriteFile(HttpResponseBase response)
        {
            // NB: Can't save directly to the output stream,
            // as most image formats require a seekable stream.

            using (var imageStream = new MemoryStream())
            {
                this.Chart.SaveImage(imageStream, this.ImageFormat);
                imageStream.WriteTo(response.OutputStream);
            }
        }
    }
}